<template>
  <div class="my-component">
    <div class="user-bot-index-view">
      <h1>座位预约记录</h1>

      <div class="modal" v-if="showrnotrange">
        <div class="modal-content">
          <p>{{modelmessage}}</p>
          <button @click="closeModal()">确认</button>
        </div>
      </div>

      <div class="table-container">
        <table class="table">
          <thead>
            <tr>
              <th>日期 + 时间段</th>
              <th>预约座位</th>
              <th>预约时间</th>
              <th>预约取消</th>
              <th>签到</th>
              <th>离开位置</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="reservation in dueHistoryList" :key="reservation.id">
              <td>{{ reservation.date +' '+ reservation.time }}</td>
              <td>{{ reservation.seatid }}</td>
              <td>{{ reservation.duetime }}</td>
              <td>{{ reservation.iscancel ? '是' : '否' }}</td>
              <td>
                <button @click="handleSignIn(reservation)" :disabled="reservation.issignin">
                  {{ reservation.issignin ? '是' : '否' }}
                </button>
              </td>
              <td>{{ reservation.isout ? '是' : '否' }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 弹屏提示 -->
      <div class="tips" v-if="showMsg">
        <div class="messagetext">
          {{ message }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import { ref, onMounted } from "vue";
import { useStore } from "vuex";

export default {
  name: "UserDueHistoryView",
  setup() {
    const dueHistoryList = ref([]);
    const store = useStore();

    // 获取当前用户的预约记录
    const getCurrentUser = () => {
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/getDueHistory",
        type: "GET",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },

        dataType: "json",
        success: (data) => {
          console.log("当前登录用户信息：", data[0].userid);
          dueHistoryList.value = data;
        },

        error: (xhr, status, error) => {
          console.error("获取当前登录用户信息失败", error);
        },
      });
    };

    onMounted(() => {
      getCurrentUser();
    });

    return {
      dueHistoryList,
    };
  },

  data() {
    return {
      showrnotrange: false,
      modelmessage:"",  // 模态框内容
      showMsg: false,  // 弹屏
      message: "",  // 弹屏内容
    };
  },

  methods: {
    //弹屏提示信息
    showMessageFun(msg = "提示", time = 3000) {
      // let that = this;
      this.message = msg;
      this.showMsg = true;
      setTimeout(() => {
        this.showMsg = false;
      }, time);
    },
    // 处理签到按钮点击事件
    handleSignIn(reservation) {
      // 如果已经取消预约了，就不能再进行签到
      if(reservation.iscancel)
      {
        this.showMessageFun("该预约已取消，不能进行签到");
        return;
      }

      /*
      * 获取当前点击的预约记录所预约的时间
      * 
      * 判断当前时间是否在预约的时间 开始时间 前后10分钟内
      * 如果是，则执行签到操作
      * 否则，不能进行签到
      * 
      * 如果在预约的时间段内预约该时间段，则从预约时计时10分钟内进行签到，超时无法签到。
      * 通过比较预约时间是否在预约时间段内进行判断
      */
      const currentDate = new Date();
      const dueDateTime = new Date(reservation.duetime);  // 预约的时候的时间
      
      const start = reservation.time.split("~")[0].trim();  // 预约时间段开始时间
      const reservationStart = new Date(reservation.date + " " + start);  // 预约时间段开始日期+时间

      const end = reservation.time.split("~")[1].trim();  // 预约时间段结束时间
      const reservationEnd = new Date(reservation.date + " " + end);  // 预约时间段结束日期+时间

      // 计算开始时间前后10分钟的时间范围
      const startTimeRange = new Date(reservationStart);  //开始时间前十分钟
      startTimeRange.setMinutes(startTimeRange.getMinutes() - 10);
      const endTimeRange = new Date(reservationStart);  // 开始时间后十分钟
      endTimeRange.setMinutes(endTimeRange.getMinutes() + 10);

      // 预约时间在时间段内判断是否可签到
      const isInSlot = dueDateTime >= reservationStart && dueDateTime <= reservationEnd;  // 预约的时候时间是否在时间段内
      const signInEndTime = new Date(dueDateTime);  // 签到结束时间
      signInEndTime.setMinutes(signInEndTime.getMinutes() + 10);  // 签到结束时间后
      
      // 判断是否可以签到逻辑
      if(currentDate >= startTimeRange && currentDate <= endTimeRange
              || isInSlot && currentDate <= signInEndTime){
        console.log("可以签到");
        this.showMessageFun('签到成功');
        $.ajax({
          url: "http://127.0.0.1:3000/user/account/signin/",
          type: "post",
          headers: {
            Authorization: "Bearer " + this.$store.state.user.token,
          },
          data: {
            seatId: reservation.seatid,
            selectedDateSlot: reservation.date,
            selectedTimeSlot: reservation.time
            // userId: reservation.userid
          },
          success: function(response) {
            // 处理后端返回的响应
            console.log(response);
            reservation.issignin = 1;
          },
          error: function(error) {
            // 处理请求错误
            console.error(error);
          }
        });
      }
      else if(isInSlot && currentDate > signInEndTime)
      {
        this.showrnotrange = true;
        this.modelmessage = "已超过签到时间";
        console.log("已超过签到时间");
      }
      else
      {
        this.showrnotrange = true;
        this.modelmessage = "不在签到时间范围内";
        console.log("不在签到时间内");
      }
    },
    closeModal(){
      this.showrnotrange = false;
    }
    
  },

};
</script>

<style scoped>
.my-component {
  background-image: url('@/assets/images/image2.png');
  background-size: cover;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.user-bot-index-view {
  margin: 20px;
}

.table-container {
  max-height: 500px; /* 设置最大高度 */
  overflow-y: auto; /* 启用垂直滚动条 */
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,td {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden;
  text-overflow: ellipsis; /* 超出部分用省略号表示 */
  padding: 10px;
  text-align: center;
}

th {
  background-color: #f2f2f2;
}

tr:nth-child(even) {
  background-color: #f2f2f2;
}

tr:nth-child(odd) {
  background-color: #fff;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  /* 确保模态框在其他元素之上 */
}
.modal-content {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
  /* 添加阴影效果 */
  max-width: 422px;
  /* 控制模态框的最大宽度 */
  width: 90%;
  /* 控制模态框的宽度 */
}
.tips {
  position: fixed;
  top: 60px;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.messagetext {
  display: inline-block;
  height: 40px;
  line-height: 40px;
  background: rgba(0, 0, 0, 0.6);
  padding: 0 60px;
  font-size: 18px;
  border-radius: 5px;
  color: #ffffff;
  box-shadow: 0px 0px 3px 2px rgba(0, 0, 0, 0.12);
}
</style>
